package com.zhuqi.wx.pay.notify;

import cn.hutool.core.exceptions.ExceptionUtil;
import com.zhuqi.wx.pay.notify.handel.NotifyHandelResponse;
import com.zhuqi.wx.pay.service.WxPayService;
import com.zhuqi.wx.vo.WxPayOrderNotifyResultVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @author : ZhuQi
 * @version : 时间:2021/12/7 13:59 版本:
 * @description :
 */
@Slf4j
@Component
public class WxNotify {

    private String data;

    private NotifyHandelResponse notifyHandelResponse;

    private WxPayService wxPayService;

    public WxNotify(NotifyHandelResponse notifyHandelResponse, WxPayService wxPayService) {
        this.notifyHandelResponse = notifyHandelResponse;
        this.wxPayService = wxPayService;
    }

    /**
     * 构建 当前对象
     * @param xmlData
     * @param notifyHandelResponse
     * @return
     */
    public WxNotify build(String xmlData, NotifyHandelResponse notifyHandelResponse) {
        this.data = xmlData;
        this.notifyHandelResponse = notifyHandelResponse;
        return this;
    }

    /**
     * 处理微信支付回掉
     * @return
     */
    public WxPayOrderNotifyResultVo handleNotifyResult() {
        log.info("微信支付回掉原始信息:" + data);
        WxPayOrderNotifyResultVo wxPayOrderNotifyResultVo = null;

        try {
            wxPayOrderNotifyResultVo = wxPayService.parseOrderNotifyResult(data);

            if (isOk(wxPayOrderNotifyResultVo)) {
                wxPayOrderNotifyResultVo.success(
                        notifyHandelResponse.success(wxPayOrderNotifyResultVo, wxPayOrderNotifyResultVo.getData().toString())
                );

                // 执行业务代码
                doSomeThing();
                // 修改订单状态
                updateOrder(wxPayOrderNotifyResultVo);
            } else {
                wxPayOrderNotifyResultVo.success(
                        notifyHandelResponse.fail(wxPayOrderNotifyResultVo, wxPayOrderNotifyResultVo.getData().toString())
                );

                // 执行业务代码
                doSomeThing();
            }
        } catch (Exception e) {
            log.info("微信支付回掉异常:{}", ExceptionUtil.getMessage(e));
        }
        return wxPayOrderNotifyResultVo;
    }

    /**
     * 是否支付成功
     *
     * @param wxPayOrderNotifyResult 微信支付结果
     * @return true成功
     */
    private boolean isOk(WxPayOrderNotifyResultVo wxPayOrderNotifyResult) {
        return
                "SUCCESS".equals(wxPayOrderNotifyResult.getInfo()) && "SUCCESS".equals(wxPayOrderNotifyResult.getInfo());
    }


    /**
     * 执行某种业务代码
     */
    private void doSomeThing() {
        System.out.println("执行业务代码");
    }

    /**
     * 修改订单状态
     * @param wxPayOrderNotifyResultVo
     */
    private void updateOrder(WxPayOrderNotifyResultVo wxPayOrderNotifyResultVo) {
        System.out.println("修改订单");
    }

}
